import { execSync } from 'child_process'
import { isIPv4 } from 'net'
import { exec } from 'sudo-prompt'

import prompts from 'prompts'
async function add() {
  let result: prompts.Answers<'ipv4' | 'port' | 'wslIpv4' | 'wslPort'>

  // 获取wsl的ip地址
  const Ipv4Wsl = execSync('wsl hostname -I', { encoding: 'utf8' }).trim().split(' ')[0]

  try {
    result = await prompts(
      [
        {
          type: 'text',
          name: 'ipv4',
          message: '请输入宿主机 ipv4',
          initial: '*',
          validate: (value: string) => {
            if (!isIPv4(value) && value !== '*') {
              return '请输入正确的 ipv4 地址'
            }
            return true
          }
        },
        {
          type: 'number',
          name: 'port',
          message: '请输入宿主机端口',
          min: 1,
          max: 65535,
          validate: (value: number) => {
            if (value < 1 || value > 65535) {
              return '请输入 1 - 65535 之间的数字'
            }
            return true
          }
        },
        {
          type: 'text',
          name: 'wslIpv4',
          message: '请输入 wsl ipv4',
          initial: Ipv4Wsl,
          validate: (value: string) => {
            if (!isIPv4(value)) {
              return '请输入正确的 ipv4 地址'
            }
            return true
          }
        },
        {
          type: 'number',
          name: 'wslPort',
          message: '请输入 wsl 端口',
          min: 1,
          max: 65535,
          // // 默认与宿主机端口一致
          // initial: (_, { port }: { port: number }) => port,
          validate: (value: number) => {
            if (value < 1 || value > 65535) {
              return '请输入 1 - 65535 之间的数字'
            }
            return true
          }
        }
      ],
      {
        onCancel: () => {
          throw new Error('✖' + ' 操作被取消')
        }
      }
    )
  } catch (cancelled: any) {
    console.log(cancelled.message)
    return
  }

  const { ipv4, port, wslIpv4, wslPort } = result

  exec(
    `netsh interface portproxy add v4tov4 listenaddress=${ipv4} listenport=${port} connectaddress=${wslIpv4} connectport=${wslPort}`,
    {
      name: 'netsh wsl'
    },
    function (error, stdout, stderr) {
      if (error) throw error
      require('../ls/index')
      console.log(
        `New-NetFirewallRule -DisplayName "Allow Inbound TCP Port ${port}" -Direction Inbound -Action Allow -Protocol TCP -LocalPort ${port}`
      )
    }
  )
}
add()
